package com.lottery.utils;

import com.lottery.dao.qiuqiu.robotDao.RobotBetamountMapper;
import com.lottery.dao.qiuqiu.robotDao.RobotInfoMapper;
import com.lottery.entity.RobotBetamount;
import com.lottery.entity.RobotInfo;
import com.lottery.initData.InitData;
import com.lottery.initData.InitUtil;
import com.lottery.obtainData.AchieveDataImpl.BJSCAchieveDataImpl;
import com.lottery.obtainData.AchieveDataImpl.SscAchieveDataImpl;
import com.lottery.obtainData.SscYesWinningFactory.InitUtils;
import com.lottery.obtainData.SscYesWinningFactory.SscYesWinningImpl;
import com.lottery.service.pc28.robotService.RobotUserService;
import com.lottery.service.qiuqiu.MsgService.MsgNoticeService;
import com.lottery.service.qiuqiu.lobbyService.LotteryDrawService;
import com.lottery.utils.lobbyUtils.impl.BjscPlayUtilImpl;
import com.lottery.utils.lobbyUtils.impl.SscPlayutilImpl;
import com.lottery.utils.robotThread.BJSCRobotThread;
import com.lottery.utils.robotThread.SscRobotThread;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisPubSub;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Component
public class RedisMsgPubSub extends JedisPubSub {
    @Autowired
    private InitUtils initUtils;

    @Resource
    private RobotInfoMapper robotInfoDao;

    @Resource
    private SscRobotThread ssc;

    @Resource
    private BJSCRobotThread bjsc;

    @Resource
    private BjscPlayUtilImpl bjscPlayutil;

    @Resource
    private SscPlayutilImpl sscPlayutil;

    @Resource
    private MsgNoticeService msgServie;

    @Resource
    private RobotBetamountMapper robotDao;

    @Resource
    private InitUtil init;

    // private RobotUserService robotUserService;
    //
    // public RobotUserService getRobotUserService() {
    // return robotUserService;
    // }
    //
    // public void setRobotUserService(RobotUserService robotUserService) {
    // this.robotUserService = robotUserService;
    // }
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void unsubscribe() {
        super.unsubscribe();
    }

    @Override
    public void unsubscribe(String... channels) {
        super.unsubscribe(channels);
    }

    @Override
    public void subscribe(String... channels) {
        super.subscribe(channels);
    }

    @Override
    public void psubscribe(String... patterns) {
        super.psubscribe(patterns);
    }

    @Override
    public void punsubscribe() {
        super.punsubscribe();
    }

    @Override
    public void punsubscribe(String... patterns) {
        super.punsubscribe(patterns);
    }

    /*
     * (non-Javadoc) channal订阅的频道 s robot开关 A 活跃度
     */
    @Override
    public void onMessage(String channel, String message) {
        logger.debug("channel:" + channel + " receives message :" + message);
//        if (message != null && !message.equals("")) {
//            if (message.startsWith("S")) {
//                int bestart = Integer.parseInt(message.substring(1, message.length()));
//                if (bestart == 0) {
//                    robotUserService.robotLogout();
//                    RobotParams.bestart = false;
//                }
//                if (bestart == 1) {
//                    RobotParams.bestart = true;
//                    robotUserService.robotLogin();
//                }
//            } else if (message.startsWith("A")) {
//                int ac = Integer.parseInt(message.substring(1, message.length()));
//                if (RobotParams.activeNum != ac) {
//                    logger.info("**************** activeNum is " + ac + "****************************");
//                    RobotParams.activeNum = ac;
//                    // robotUserService.robotLogin();
//                }
//            } else if (message.startsWith("BMIN")) {
//                int min = Integer.parseInt(message.substring(4, message.length()));
//                RobotParams.robotBetMin = min;
//            } else if (message.startsWith("BMAX")) {
//                int max = Integer.parseInt(message.substring(4, message.length()));
//                RobotParams.robotBetMax = max;
//            } else if (message.startsWith("OMIN")) {
//                int min = Integer.parseInt(message.substring(4, message.length()));
//                RobotParams.onlineNumMin = min;
//            } else if (message.startsWith("OMAX")) {
//                int max = Integer.parseInt(message.substring(4, message.length()));
//                RobotParams.onlineNumMax = max;
//            }
        if (message.startsWith("robot")) {
            //指令robot/88888   机器人/渠道商标识
            String[] split = message.split("/");
            String agencyMark = split[1];
            judgeRobotInfo(agencyMark);
        } else if (message.startsWith("initOdd")) {
            //接收后台发送的刷新缓存的指令,刷新odd缓存
            String[] split = message.split("/");
            Thread thread = new Thread(() -> {
                int lotteyType = Integer.parseInt(split[1]);
                synchronized (String.class) {
                    while (true) {
                        if (lotteyType == 1) {
                            if (LotteryDrawService.sscbl) {
                                init.initODD_MAP(lotteyType);
                                break;
                            } else {
                                try {
                                    Thread.sleep(10 * 1000);
                                } catch (InterruptedException e) {
                                    logger.error("ssc initODD error,{}", e);
                                }
                            }
                        } else if (lotteyType == 3) {
                            if (LotteryDrawService.bjscbl) {
                                init.initODD_MAP(lotteyType);
                                break;
                            } else {
                                try {
                                    Thread.sleep(10 * 1000);
                                } catch (InterruptedException e) {
                                    logger.error("bjsc initODD error,{}", e);
                                }
                            }
                        }
                    }
                }
            });
            thread.start();
        }

    }

    //对发出的机器人指令做处理
    private void judgeRobotInfo(String agencyMark) {
        int num = Integer.parseInt(agencyMark);
        RobotBetamount ro = robotDao.searchByAgency(num);
        if (null == ro) {
            logger.error("数据库不存在数据,请检查数据库");
        } else {
            String lotteyType = ro.getLotteyType();
            String[] split = lotteyType.split(",");
            for (String ss : split) {
                if ("1".equals(ss)) {
//                    ssc.agencyMark=Integer.parseInt(agencyMark);
//                    Thread thread = new Thread(ssc);
//                    thread.start();
                    Thread thread = new Thread(() -> {
                        sscThread(Integer.parseInt(agencyMark));
                    });
                    thread.start();
                } else if ("3".equals(ss)) {
//                    bjsc.agencyMark=Integer.parseInt(agencyMark);
//                    Thread thread = new Thread(bjsc);
//                    thread.start();
                    Thread thread = new Thread(() -> {
                        bjscThread(Integer.parseInt(agencyMark));
                    });
                    thread.start();
                }
            }
        }
    }

    private void bjscThread(Integer agencyMark) {
        List<RobotInfo> robotInfos = robotInfoDao.searchRobotListInfo(agencyMark);
        logger.debug("BJSCRobotThread " + agencyMark + " start");
        RobotBetamount ro = robotDao.searchByAgency(agencyMark);
        Integer moneyMax = ro.getMoneyMax();
        Integer moneyMin = ro.getMoneyMin();
        Integer robotActiveMax = ro.getRobotActiveMax();
        Integer robotActiveMin = ro.getRobotActiveMin();
        Integer baseOnline = ro.getBaseOnline();
        int robotBetOnline = RandCodeUtil.getRandNum(robotActiveMin, robotActiveMax);

        //获取渠道商正在使用的玩法下注信息
        List<Integer> playwayIdList = new ArrayList<>();
        InitData.BJSC_ODD_MAP.get(agencyMark + "").forEach((k, v) -> {
            playwayIdList.add(k);
        });
        List<String> betRuleList = new ArrayList<>();
        InitData.BJSC_BETRULE_REF_PLAYWAYID.forEach((k, v) -> {
            if (playwayIdList.contains(v)) {
                betRuleList.add(k);
            }
        });
        while (true) {
            logger.debug(Thread.currentThread().getName() + "BJSCRobotThread " + agencyMark + " start");
            RobotBetamount ro1 = robotDao.searchByAgency(agencyMark);
            if (ro1.getRobotSwitch() == 0) {
                int hour = Integer.parseInt(DateUtil.getFormatDate("HH"));
                if (hour > 2 && hour < 8) { // 这个时段机器人都下线
                    InitData.ROBOT_ONLINE_NUM.put(agencyMark + "", 0);
                    try {
                        Thread.sleep(6 * 60 * 60 * 1000);
                    } catch (InterruptedException e) { // TODO Auto-generated catch block
                        logger.error("BjscRobotThread " + agencyMark + " error ,{}", e);
                    }
                } else {
                    //下注时间判断
                    boolean timeJudge = bjscPlayutil.judgeBetTime();
                    int onlineNum = RandCodeUtil.getRandNum(robotActiveMin, robotActiveMax) + baseOnline;
                    InitData.ROBOT_ONLINE_NUM.put(agencyMark + "", onlineNum);
                    if (timeJudge) {
                        if (robotBetOnline > robotInfos.size()) {
                            robotBetOnline = robotInfos.size();
                        }
                        RobotInfo rz = robotInfos.get(RandCodeUtil.getRandNum(0, robotBetOnline - 1));
                        String bet = betRuleList.get(RandCodeUtil.getRandNum(0, betRuleList.size() - 1));
                        int money = (moneyMin + RandCodeUtil.getRandNum(0, moneyMax - moneyMin)) / 10;
                        String betRule = bet + "/" + money * 10;
                        msgServie.RobotinsertBetNotice(rz, betRule, 3, agencyMark + "");
                        //获取下注间隔时间
                        long time = 4 * 60 * 1000 / robotBetOnline;
                        try {
                            Thread.sleep(time * RandCodeUtil.getRandNum(8, 12) / 10);
                        } catch (InterruptedException e) {
                            logger.error("BjscRobotThread sleep Error ,{}", e);
                        }
                    } else {
                        robotBetOnline = RandCodeUtil.getRandNum(robotActiveMin, robotActiveMax);
                        try {
                            Thread.sleep(50 * 1000);
                        } catch (InterruptedException e) {
                            logger.error("BjscRobotThread sleep Error ,{}", e);
                        }
                    }
                }
            } else {
                InitData.ROBOT_ONLINE_NUM.put(agencyMark + "", 0);
                break;
            }
        }

    }

    private void sscThread(Integer agencyMark) {
        List<RobotInfo> robotInfos = robotInfoDao.searchRobotListInfo(agencyMark);
        RobotBetamount ro = robotDao.searchByAgency(agencyMark);
        logger.debug(Thread.currentThread().getName() + "SscRobotThread " + agencyMark + " start ******************************");
        Integer moneyMax = ro.getMoneyMax();
        Integer moneyMin = ro.getMoneyMin();
        Integer robotActiveMax = ro.getRobotActiveMax();
        Integer robotActiveMin = ro.getRobotActiveMin();
        Integer baseOnline = ro.getBaseOnline();
        int robotBetOnline = RandCodeUtil.getRandNum(robotActiveMin, robotActiveMax);

        //获取渠道商正在使用的玩法下注信息
        List<Integer> playwayIdList = new ArrayList<>();
        InitData.SSC_ODD_MAP.get(agencyMark + "").forEach((k, v) -> {
            playwayIdList.add(k);
        });
        List<String> betRuleList = new ArrayList<>();
        InitData.SSC_BETRULE_REF_PLAYWAYID.forEach((k, v) -> {
            if (playwayIdList.contains(v)) {
                betRuleList.add(k);
            }
        });
        while (true) {
            logger.debug(Thread.currentThread().getName() + "BJSCRobotThread " + agencyMark + " start");
            RobotBetamount ro1 = robotDao.searchByAgency(agencyMark);
            logger.debug(Thread.currentThread().getName() + "SscRobotThread " + agencyMark + " start ******************************");
            if (ro1.getRobotSwitch() == 0) {
                int hour = Integer.parseInt(DateUtil.getFormatDate("HH"));
                if (hour > 2 && hour < 8) { // 这个时段机器人都下线
                    InitData.ROBOT_ONLINE_NUM.put(agencyMark + "", 0);
                    try {
                        Thread.sleep(6 * 60 * 60 * 1000);
                    } catch (InterruptedException e) { // TODO Auto-generated catch block
                        logger.error("SscRobotThread " + agencyMark + " error ,{}", e);
                    }
                } else {
                    //下注时间判断
                    boolean timeJudge = sscPlayutil.judgeBetTime();
                    int onlineNum = RandCodeUtil.getRandNum(robotActiveMin, robotActiveMax) + baseOnline;
                    InitData.ROBOT_ONLINE_NUM.put(agencyMark + "", onlineNum);
                    if (timeJudge) {
                        if (robotBetOnline > robotInfos.size()) {
                            robotBetOnline = robotInfos.size();
                        }
                        RobotInfo rz = robotInfos.get(RandCodeUtil.getRandNum(0, robotBetOnline - 1));
                        String bet = betRuleList.get(RandCodeUtil.getRandNum(0, betRuleList.size() - 1));
                        int money = (moneyMin + RandCodeUtil.getRandNum(0, moneyMax - moneyMin)) / 10;
                        String betRule = bet + "/" + money * 10;
                        msgServie.RobotinsertBetNotice(rz, betRule, 1, agencyMark + "");
                        //获取下注间隔时间
                        long time = 9 * 60 * 1000 / robotBetOnline;
                        try {
                            Thread.sleep(time * RandCodeUtil.getRandNum(8, 12) / 10);
                        } catch (InterruptedException e) {
                            logger.error("sscRobotThread sleep Error ,{}", e);
                        }
                    } else {
                        robotBetOnline = RandCodeUtil.getRandNum(robotActiveMin, robotActiveMax);
                        try {
                            Thread.sleep(50 * 1000);
                        } catch (InterruptedException e) {
                            logger.error("sscRobotThread sleep Error ,{}", e);
                        }
                    }
                }

            } else {
                InitData.ROBOT_ONLINE_NUM.put(agencyMark + "", 0);
                break;
            }
        }
    }

    @Override
    public void onPMessage(String pattern, String channel, String message) {

    }

    @Override
    public void onSubscribe(String channel, int subscribedChannels) {
        // System.out.println("channel:" + channel + "is been subscribed:" +
        // subscribedChannels);
    }

    @Override
    public void onPUnsubscribe(String pattern, int subscribedChannels) {

    }

    @Override
    public void onPSubscribe(String pattern, int subscribedChannels) {

    }

    @Override
    public void onUnsubscribe(String channel, int subscribedChannels) {
        // System.out.println("channel:" + channel + "is been unsubscribed:" +
        // subscribedChannels);
    }
}
